package com.ruoyi.system.controller;

import java.io.*;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.core.io.FileUtil;
import com.alibaba.fastjson.JSON;
import com.ruoyi.common.core.domain.OaResult;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.core.utils.facade.OaBusinessFacade;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.system.api.domain.SysUser;
import io.minio.MinioClient;
import io.minio.policy.PolicyType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.log.annotation.Log;
import com.ruoyi.common.log.enums.BusinessType;
import com.ruoyi.system.domain.OaUploadZip;
import com.ruoyi.system.service.IOaUploadZipService;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.core.utils.poi.ExcelUtil;
import com.ruoyi.common.core.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 上传简历压缩包Controller
 * 
 * @author ruoyi
 * @date 2020-12-29
 */
@RestController
@RequestMapping("/zip")
public class OaUploadZipController extends BaseController
{

    private static final Logger LOGGER = LoggerFactory.getLogger(OaUploadZipController.class);

    @Value("${minio.url}")
    private String MINIO_URL;

    @Value("${minio.endpoint}")
    private String ENDPOINT;

    @Value("${minio.bucketname}")
    private String BUCKET_NAME;

    @Value("${minio.accessKey}")
    private String ACCESS_KEY;

    @Value("${minio.secretKey}")
    private String SECRET_KEY;


    @Autowired
    private IOaUploadZipService oaUploadZipService;


   // @Log(title = "上传候选人简历", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:zip:add')")
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file, boolean updateSupport, HttpServletRequest request,String processCode) throws Exception
    {

        try {
            OaResult result= OaBusinessFacade.uploadZipFile(multipartFileToFile(file),processCode);
            if("200".equals(result.getCode())){
               /* MinioClient minioClient = new MinioClient(ENDPOINT,ACCESS_KEY,SECRET_KEY);
                boolean isExist = minioClient.bucketExists(BUCKET_NAME);
                if(isExist){
                    LOGGER.info("存储桶已经存在");
                }else {
                    minioClient.makeBucket(BUCKET_NAME);
                    minioClient.setBucketPolicy(BUCKET_NAME,"*.*", PolicyType.READ_ONLY);
                }
                String filename = file.getOriginalFilename();
               //String filename = DateUtils.dateTimeNow()+"东方融创.zip";
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String objectName = "oa"+"/"+dateTimeFormatter.format(LocalDate.now())+"/"+filename;
                minioClient.putObject(BUCKET_NAME,objectName,file.getInputStream(),file.getContentType());
                LOGGER.info("上传成功");*/
                String filename = file.getOriginalFilename();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMdd");
                String objectName = "oa"+"/"+dateTimeFormatter.format(LocalDate.now())+"/"+filename;
                // Map<String,String> map = new HashMap<>(8);
                // map.put("url",MINIO_URL+"/"+BUCKET_NAME+"/"+BUCKET_NAME+"/"+objectName);

                OaUploadZip oaUploadZip=new OaUploadZip();
                oaUploadZip.setCode(result.getCode());
                oaUploadZip.setMessage(result.getMessage());
                oaUploadZip.setPath(MINIO_URL+"/"+BUCKET_NAME+"/"+BUCKET_NAME+"/"+objectName);
                oaUploadZipService.insertOaUploadZip(oaUploadZip);
                return AjaxResult.success("上传成功");
            }else if("400".equals(result.getCode())){
                return AjaxResult.success("该招聘需求已关闭");
            }

        } catch (Exception e) {
            LOGGER.info("上传发生错误:{}!",e.getMessage());
        }
        return AjaxResult.success("上传失败");
    }

    public String upload(MultipartFile file, String path, String fileName) throws Exception {
        // 生成新的文件名
        String realPath = path + "/" + UUID.randomUUID().toString().replace("-", "")+fileName.substring(fileName.lastIndexOf("."));
        File dest = new File(realPath);
        // 判断文件父目录是否存在
        if (!dest.getParentFile().exists()) {
        dest.getParentFile().mkdir();
        }
        // 保存文件
        file.transferTo(dest);
        return dest.getName();
    }

    /**
     * 查询上传简历压缩包列表
     */
    @PreAuthorize("@ss.hasPermi('system:zip:list')")
    @GetMapping("/list")
    public TableDataInfo list(OaUploadZip oaUploadZip)
    {
        startPage();
        List<OaUploadZip> list = oaUploadZipService.selectOaUploadZipList(oaUploadZip);
        return getDataTable(list);
    }

    /**
     * 导出上传简历压缩包列表
     */
    @PreAuthorize("@ss.hasPermi('system:zip:export')")
    @Log(title = "上传简历压缩包", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, OaUploadZip oaUploadZip) throws IOException
    {
        List<OaUploadZip> list = oaUploadZipService.selectOaUploadZipList(oaUploadZip);
        ExcelUtil<OaUploadZip> util = new ExcelUtil<OaUploadZip>(OaUploadZip.class);
        util.exportExcel(response, list, "zip");
    }

    /**
     * 获取上传简历压缩包详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:zip:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(oaUploadZipService.selectOaUploadZipById(id));
    }

    /**
     * 新增上传简历压缩包
     */
    @PreAuthorize("@ss.hasPermi('system:zip:add')")
    @Log(title = "上传简历压缩包", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody OaUploadZip oaUploadZip)
    {
        return toAjax(oaUploadZipService.insertOaUploadZip(oaUploadZip));
    }

    /**
     * 修改上传简历压缩包
     */
    @PreAuthorize("@ss.hasPermi('system:zip:edit')")
    @Log(title = "上传简历压缩包", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody OaUploadZip oaUploadZip)
    {
        return toAjax(oaUploadZipService.updateOaUploadZip(oaUploadZip));
    }

    /**
     * 删除上传简历压缩包
     */
    @PreAuthorize("@ss.hasPermi('system:zip:remove')")
    @Log(title = "上传简历压缩包", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(oaUploadZipService.deleteOaUploadZipByIds(ids));
    }

    public static File multipartFileToFile(MultipartFile file) throws Exception {

        File toFile = null;
        if (file.equals("") || file.getSize() <= 0) {
            file = null;
        } else {
            InputStream ins = null;
            ins = file.getInputStream();
            toFile = new File(file.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }

    //获取流文件
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
